package com.comone.webrtcaudio;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;

import com.comone.webrtcaudio.wav.AudioPlayer;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class VoicePlayer {

    private AudioTrack audioTrack;

    private void createAudioTrack(int sampleRate) {
        int minBufferSize = AudioTrack.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
    }

    public void start(int sampleRate) {
        createAudioTrack(sampleRate);
        if (audioTrack.getState() == AudioTrack.STATE_INITIALIZED) audioTrack.play();
        else {
            for (int i = 0; i < 3; i++) {
                createAudioTrack(sampleRate);
                if (audioTrack.getState() == AudioTrack.STATE_INITIALIZED) {
                    audioTrack.play();
                    break;
                }
            }
        }
    }

    private List<short[]> frames = new ArrayList<>();
    public void write(short[] frame) {
        if (frame == null) return;
//        audioTrack.write(byteArray2ShortArray(frame), 0, frame.length * 2);
        audioTrack.write(frame, 0, frame.length);
//        synchronized (frames){
//            {
//                double sum = 0;
//                int i;
//                try {
//                    for (i = 0; i < frame.length; i++) {
//                        sum = sum + frame[i];
//                    }
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//                Log.e("" , "resultFrame" + sum);
//            }
//            frames.add(frame);
//        }
    }

    public void play(){
        AudioPlayer audioPlayer = new AudioPlayer();
        audioPlayer.startPlayer(0);
        synchronized (frames){
            frames.forEach(new Consumer<short[]>() {
                @Override
                public void accept(short[] frame) {
                    audioPlayer.play(byteArray2ShortArray(frame), 0, frame.length * 2);
//                audioTrack.write(frame, 0, frame.length);
                }
            });
        }
    }

    public static byte[] byteArray2ShortArray(short[] data) {
        byte[] bytes2 = new byte[data.length * 2];
        ByteBuffer.wrap(bytes2).asShortBuffer().put(data);
        return bytes2;
    }

    public void stopPlaying() {
        if (audioTrack.getState() == AudioTrack.STATE_INITIALIZED) audioTrack.stop();
        audioTrack.flush();
    }
}